package com.eastmelon.blog.controller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.NoSuchAlgorithmException;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.eastmelon.blog.exception.BlogException;
import com.eastmelon.blog.service.UserService;
import com.eastmelon.blog.util.SecurityCode;
import com.eastmelon.blog.util.SecurityImage;
import com.eastmelon.blog.util.SecurityUtil;

@Controller("loginController")
public class LoginController {
	// 图片流
	private ByteArrayInputStream imageStream;

	public ByteArrayInputStream getImageStream() {
		return imageStream;
	}

	public void setImageStream(ByteArrayInputStream imageStream) {
		this.imageStream = imageStream;
	}

	@Resource(name = "userService")
	private UserService userService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "login";
	}
	
	@RequestMapping(value="/login.do",method=RequestMethod.POST)
	public String login(String username,String password,String checkcode,Model model,HttpSession session) throws NoSuchAlgorithmException {
		String cc = (String)session.getAttribute("cc");
		if(!cc.equals(checkcode)) {
			model.addAttribute("error","验证码出错，请重新输入");
			return "login";
		}
		Subject suser = SecurityUtils.getSubject();
		String realPass=SecurityUtil.md5(username, password);
		UsernamePasswordToken token = new UsernamePasswordToken(username,realPass);
		token.setRememberMe(true);
		try {
			suser.login(token);
			return "redirect:/back/index.do";
		}catch (AuthenticationException e) {
			token.clear();
			throw new BlogException("用户名或密码错误");
		}
	}

	@RequestMapping("/drawCheckCode.do")
	public void drawCheckCode(HttpServletResponse resp, HttpSession session)
			throws IOException {
		// 如果开启Hard模式，可以不区分大小写
		// String securityCode = SecurityCode.getSecurityCode(4,SecurityCodeLevel.Hard,
		// false).toLowerCase();
		// 获取默认难度和长度的验证码
		String checkcode = SecurityCode.getSecurityCode();
		session.setAttribute("cc", checkcode);
		OutputStream os = resp.getOutputStream();
		ImageIO.write(SecurityImage.createImage(checkcode), "jpg", os);
	}
}
